﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace MyAMS.WebServer.ActionFilter
{
    /// <summary>
    /// 控制器动作规则
    /// </summary>
    public class ControllerActionCriteria : IActionFilterCriteria
    {
        private readonly List<ReflectedActionDescriptor> methods = new List<ReflectedActionDescriptor>();

        /// <summary>
        /// 添加一个方法进入规则
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        public void AddMethod<T>(Expression<Func<T, object>> method)
        {
            MethodCallExpression methodCall = method.Body as MethodCallExpression;

            if (methodCall == null)
            {
                //TODO: (5he11) 抛异常 throw new InvalidOperationException();
            }
            methods.Add(new ReflectedActionDescriptor(methodCall.Method, methodCall.Method.Name, new ReflectedControllerDescriptor(methodCall.Object.Type)));
        }

        /// <summary>
        /// 决定某控制器上下文和动作说明器是否符合当前标准
        /// </summary>
        /// <param name="controllerContext">控制器上下文</param>
        /// <param name="actionDescriptor">动作说明器</param>
        /// <returns></returns>
        public bool Match(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            ReflectedActionDescriptor reflectedDescriptor = actionDescriptor as ReflectedActionDescriptor;
            return reflectedDescriptor != null ? methods.Any(a => a.MethodInfo == reflectedDescriptor.MethodInfo) : methods.Any(a => a.ControllerDescriptor.FindAction(controllerContext, actionDescriptor.ActionName) != null);
        }
    }
}
